package com.cn.ycy.service;

import com.cn.ycy.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
public class UserMapperTranstationServiceImpl {

    @Autowired
    UserMapperServiceImpl userMapperService;

    /**
     * 独立的事务,互不影响
     */
    public void insert10and10() {
        userMapperService.insert10();
        userMapperService.insert10();
    }

    /**
     * 都在事务
     */
    @Transactional
    public void in11() {
        userMapperService.insert11();
        userMapperService.insert12();
        userMapperService.insert12();
    }

    /**
     * 一定要注意
     * * 虽然 insert10() 没有声明注解 @Transactional,但是外层方法声明了 @Transactional，
     * * 所以 insert10() 也加入到事务中去了
     * <p>
     * 原理就是把connection 绑定到当前线程。
     * <p>
     * spring-mybatis
     * 获取和提交connection的时候 ，都是统一用了静态方法 从当前线程中获取 connection
     * 获取 Connection con = DataSourceUtils.getConnection(obtainDataSource());
     * 提交 DataSourceUtils.releaseConnection(con, getDataSource());
     * ConnectionHolder conHolder = (ConnectionHolder) TransactionSynchronizationManager.getResource(dataSource);
     */
    @Transactional
    public void insert10and11() {
        userMapperService.insert10();
        userMapperService.insert11();
        userMapperService.insert11();
    }

    @Transactional
    public void rollerbackExp() {
        try {
            userMapperService.rollerbackExp();
        } catch (Exception e) {
            e.printStackTrace();
        }
        userMapperService.insert();
    }

    public void rollerbackExp3() {
        rollerbackExp1();
    }

    public void rollerbackExp1() {
        throw new RuntimeException();
    }

}
